import axios from 'axios'
import md5 from 'js-md5'
axios.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest';
axios.defaults.headers.get['X-Requested-With'] = 'XMLHttpRequest';


// 创建 axios 实例
const service = axios.create({
    baseURL: 'http://gw.hsjt.group', // 替换为你的 API 基础地址
});

function createSigin(){
    let appid = '15600733ab1faa5c4968206714837a7b'
    let key = 'e81cdeb2ca45e91e994840818b829ff3be7c200c'
    let timeout = parseInt(new Date().getTime()/1000)
    return {
        'appId': appid,
        'timeOut': timeout,
    }
}
function signStringify(obj) {
    var arr = [];
    var params = '';

    for (var item in obj) {
        // 将所有非空参数(不为null,不为"",不为"   ")
        if (typeof obj[item] !== 'object') {
            if (obj[item] !== null && !/^\s*$/.test(obj[item]) && obj[item] != '' && obj[item] != '0' && obj[item] !== undefined) {
                if (typeof obj[item] === 'boolean') {
                    params = item.toLowerCase() + '=' + (obj[item] ? 'true' : 'false');
                } else {
                    params = item.toLowerCase() + '=' + obj[item];
                }
                arr.push(params);
            }
        }
    }
    arr.sort();
    return arr;
}


// 请求拦截器
service.interceptors.request.use(
    config => {
        let Sign = ''
        let num = 0
        let obj =  {
            'appid':  createSigin().appId,
            'key': 'e81cdeb2ca45e91e994840818b829ff3be7c200c',
            'nowtime': createSigin().timeOut,
        }
        if(config.data){
            for( let i in config.data){
                if(typeof config.data[i] == 'object'){
                    break;
                } else {
                    obj[i] = config.data[i]
                }
            }
        }
        obj = signStringify(obj)
        for(let i in obj){
            num++
            if(num < Object.getOwnPropertyNames(obj).length-1){
                Sign += `${obj[i]}` + 'HSJT&GW'
            } else {
                Sign += `${obj[i]}`
            }
        }
        config.headers.sign = md5(Sign).toUpperCase()
        config.headers.nowtime = createSigin().timeOut
        config.headers.appid = createSigin().appId
        return config
    },
    (error) => {
        // 处理请求错误
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response) => {
        return response.data;
    },
    (error) => {
        // 处理响应错误
        console.error('响应出错:', error);
        return Promise.reject(error);
    }
);

// 导出请求方法
const request = {
    get(url, params) {
        return service.get(url, { params });
    },
    post(url, data) {
        return service.post(url, data);
    },
    put(url, data) {
        return service.put(url, data);
    },
    delete(url, params) {
        return service.delete(url, { params });
    },
};

export default request;